package com.yingpai.fitness.dvp_2_0.main.activity.mine.shop_refund;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.Permission;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.GsonUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.bean.Dvp_2_1_OrderListBean;
import com.yingpai.fitness.dvp_2_0.main.bean.shop_refund.RefundReasonBean;
import com.yingpai.fitness.dvp_2_0.main.bean.shop_refund.RefundServiceBean;
import com.yingpai.fitness.dvp_2_0.main.util.DialogUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;
import com.yingpai.fitness.entity.ShopDetailMcipChildBean;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import io.reactivex.functions.Consumer;

/**
 * Created by ASUS on 2018/11/28.
 */

public class RefundServiceActivity extends CommonActivity {
    @BindView(R.id.photo)
    ImageView photo;
    @BindView(R.id.rc_layout)
    RCRelativeLayout rcLayout;
    @BindView(R.id.item_title)
    TextView item_title;
    @BindView(R.id.num_spec)
    TextView numSpec;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.reason)
    TextView reason;
    @BindView(R.id.select_tv)
    TextView selectTv;
    @BindView(R.id.money_tv)
    TextView moneyTv;
    @BindView(R.id.instruction)
    EditText instruction;
    @BindView(R.id.photo_ll)
    LinearLayout photoLl;
    @BindView(R.id.photo_num)
    TextView photoNum;
    @BindView(R.id.take_photo)
    LinearLayout takePhoto;
    @BindView(R.id.take_photo_ll)
    LinearLayout take_photo_ll;
    private String strTitle;
    private Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean detailListBean;
//    private OrderListBean.MapBean.PageInfoBean.ListBean.DetailListBean detailListBean;
    private List<File> imageList;
    private int photo_num = 3;
    private QuickAdapter<RefundReasonBean.DataBean> quickAdapter;
    private int refundMark = 0;
    private int orderId;
    private String reasonCode = "-1";
    private DecimalFormat df = new DecimalFormat("######.###");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_retund_service);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            strTitle = bundle.getString("tag");
            if(strTitle.equals("退款")){
//                take_photo_ll.setVisibility(View.GONE);
                refundMark = 0;
            }else{
                refundMark = 1;
            }
            orderId = bundle.getInt("orderId",0);
//            detailListBean = (OrderListBean.MapBean.PageInfoBean.ListBean.DetailListBean) bundle.getSerializable("DetailListBean");
            detailListBean = (Dvp_2_1_OrderListBean.DataBean.PageInfoBean.ListBeanX.DetailListBean.ListBean) bundle.getSerializable("DetailListBean");
            setTitle(strTitle);
            Glide.with(this)
                    .load(detailListBean.getPhotoUrl())
                    .error(R.mipmap.default_small_bg)
                    .into(photo);
            //rcLayout.setClipBackground(true);
            rcLayout.setTopLeftRadius(6);
            rcLayout.setTopRightRadius(6);
            rcLayout.setBottomLeftRadius(6);
            rcLayout.setBottomRightRadius(6);
            item_title.setText(detailListBean.getMerchandiseName());
            money.setText("￥" + df.format(detailListBean.getSinglePrice() / 100));
            List<ShopDetailMcipChildBean> mcipList = GsonUtil.jsonToList(detailListBean.getMcipValue(), ShopDetailMcipChildBean.class);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < mcipList.size(); i++) {
                if (i == mcipList.size() - 1) {
                    stringBuilder.append(mcipList.get(i).getPropertyValue());
                } else {
                    stringBuilder.append(mcipList.get(i).getPropertyValue() + ";");
                }
            }
            numSpec.setText("数量：x" + detailListBean.getPurchaseAmount() + ";" + stringBuilder.toString());
            moneyTv.setText("￥" + df.format(detailListBean.getSinglePrice() / 100));
        }

        imageList = new ArrayList<>();
    }

    @Override
    protected void initData() {

    }

    @Override
    @OnClick({R.id.reason_rl, R.id.take_photo, R.id.submit})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.reason_rl:
                showDialog(this, null);
                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_REFUND_REASON,
                        null, Url.GET_REFUND_REASON, new Callback<RefundReasonBean>() {
                    @Override
                    public void onSuccess(RefundReasonBean refundReasonBean) {
                        dismissDialog();
                        if (refundReasonBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                            DialogUtil.getInstance().showBottomDialog(context, R.layout.refund_select_reason);
                            View dialog_select_reason = DialogUtil.getInstance().dialog_bottom_layout;
                            dialog_select_reason.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                }
                            });
                            ListView listView = dialog_select_reason.findViewById(R.id.listview);
                            quickAdapter = new QuickAdapter<RefundReasonBean.DataBean>(context, R.layout.item_string) {
                                @Override
                                protected void convert(BaseAdapterHelper helper, RefundReasonBean.DataBean item) {
                                    helper.setText(R.id.content, item.getName());
                                }
                            };
                            listView.setAdapter(quickAdapter);

                            quickAdapter.clear();
                            quickAdapter.addAll(refundReasonBean.getData());
                            quickAdapter.notifyDataSetChanged();

                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    reasonCode = quickAdapter.getItem(position).getCode();
                                    reason.setText(quickAdapter.getItem(position).getName());
                                    selectTv.setVisibility(View.INVISIBLE);
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                }
                            });
                        } else {
                            showToast(refundReasonBean.getMessage() + "");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
                break;
            case R.id.take_photo:
                if (rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showTakePhotoOrAlbumDialog();
                } else {
                    rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Permission>() {
                                @Override
                                public void accept(Permission permission) throws Exception {
                                    if (permission.granted) {
                                        // 用户已经同意该权限
                                        showTakePhotoOrAlbumDialog();
                                    } else if (permission.shouldShowRequestPermissionRationale) {
                                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                        showToast("拒绝权限可能导致部分功能不能使用");
                                    } else {
                                        // 用户拒绝了该权限，并且选中『不再询问』
                                        showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                                    }
                                }
                            });
                }
                break;
            case R.id.submit:
                if(!reasonCode.equals("-1")){
                    showDialog(this, null);
                    HashMap<String,Object> map = new HashMap<>();
                    map.put("merchandiseOrderId",orderId);
                    map.put("orderDetailId",detailListBean.getId());
                    map.put("refundCase",reasonCode);
                    map.put("refundDescription",instruction.getText().toString().trim());
                    map.put("refundMark",refundMark);
                    map.put("__files",imageList);

                    finalOkGo.requestEncrypt(RequestType.POSTFILESENCRYPT, Contacts.HOST_SERVER + Url.SUBMIT_REFUND, map, Url.SUBMIT_REFUND, new Callback<RefundServiceBean>() {
                        @Override
                        public void onSuccess(RefundServiceBean refundServiceBean) {
                            dismissDialog();
                            if(refundServiceBean.getCode().equals(Constant.REQUEST_SUCCESS_0)){
                                EventBus.getDefault().post("updateOrderList");
                                Bundle bundle = new Bundle();
                                bundle.putString("refundMark",refundMark+"");
                                bundle.putString("refundId",refundServiceBean.getData().getId());
                                startFinishActivity(RefundServiceDetailActivity.class,bundle);
                            }else{
                                showToast(refundServiceBean.getMessage()+"");
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                }else{
                    showToast("请填写退款原因");
                }

                break;
        }
    }

    private void showTakePhotoOrAlbumDialog() {
        TDialog tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.take_photos_dialog_layout)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_open_album, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
                                FunctionConfig camera = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .build();
                                //带配置
                                GalleryFinal.openCamera(300, camera, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 300) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (imageList.size() < 3) {
                                                    imageList.add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = View.inflate(context, R.layout.item_refund_image, null);
                                                    view.setTag(imageList.get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(context)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    Log.e("finali", view.getTag() + "");
                                                                    photo_num = photo_num + 1;
                                                                    imageList.remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    takePhoto.setVisibility(View.VISIBLE);
                                                                    photoNum.setText(photo_num + "/" + 3);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (imageList.size() == 3) {
                                                takePhoto.setVisibility(View.GONE);
                                            }
                                            photo_num = photo_num - resultList.size();
                                            photoNum.setText(photo_num + "/" + 3);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_open_album:
                                FunctionConfig album = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setEnablePreview(true)
                                        .setMutiSelectMaxSize(photo_num)
                                        .build();
                                //带配置
                                GalleryFinal.openGalleryMuti(200, album, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 200) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (imageList.size() < 3) {
                                                    imageList.add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = View.inflate(context, R.layout.item_refund_image, null);
                                                    view.setTag(imageList.get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(context)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    photo_num = photo_num + 1;
                                                                    Log.e("finali", view.getTag() + "");
                                                                    imageList.remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    takePhoto.setVisibility(View.VISIBLE);
                                                                    photoNum.setText(photo_num + "/" + 3);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (imageList.size() == 3) {
                                                takePhoto.setVisibility(View.GONE);
                                            }
                                            photo_num = photo_num - resultList.size();
                                            photoNum.setText(photo_num + "/" + 3);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:

                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

}
